/*
 * art-template.pager v1.0
 * 基于artTemplate的列表管理工具
 * 这个类只负责数据加载，分页和调用juier渲染，具体html展示在配置中传入juier模板ID
 * 
 * 依赖：
 * jquery 1.11.3 核心工具类库，本工具是作为jquery插件编写的
 * art-template-4.12.2 js模板工具，可自行修改代码替换
 * layer-v2.2 异步加载时等待动画，自行修改数据加载处的动画处理
 * 
 * @copyright 2016 huangyi 
 */

;(function($){
	//  Don't throw any errors when jQuery missing
	if(!$) {
		return console.warn('pager needs jQuery');
	}
	if(!template) {
		return console.warn('pager needs artTemplate');
	}
	if(!layer){
		return console.warn('pager needs layer');
	}
	
	$.fn.pager = function(options){
		
		var self = this;
		//temp template engine
		var tplRender = null;
		
		//temp paging template engine
		var pagintTplRender = null;
		
		var defaultOption = {
				renderType : 'replace',//渲染的方式,追加(append),替换(replace)
				tplId:'',
				pagingTplId:'',
				pagingNum:5,
				pagingId:'',
				url : '',
				startField : 'start',
				numField : 'num',
				params : {},
				animation:true,//开启数据呈现时淡入淡出动画
				data : null, //数据
				ajax : {
					type : 'json',
					method : 'get'
				},
				event :{
					onDidLoaded : function(page,totalPage,data){},
					afterRender : function(){}
				}
		};
		
		//递归合并
		var opts = $.extend(true,{},defaultOption,options);
		
		var page = {
				num : 20,//per page data num
				start : 1,//start page num
				total : 0//total records num
		};
		
		self._init = function(){
			//init template engine
			var tpl = $("#"+opts.tplId).html();
			self.tplRender = template.compile(tpl); 
			
			//init paging template enging
			if(opts.pagingId && opts.pagingId != '' && opts.pagingTplId && opts.pagingTplId != ''){
				var pagingTpl = $("#"+opts.pagingTplId).html();
				self.pagingTplRender = template.compile(pagingTpl);
			}
			
			//get default params if params in option is function
			var p = {};
			if($.isFunction(opts.params)){
				p = opts.params();
			}else{
				p = opts.params;
			}
			page.num = p[opts.numField] ? p[opts.numField] : page.num;
			page.start = p[opts.startField] ? p[opts.startField] : page.start;
		}
		
		self.next = function(){
			
			if(page.start < self._getTotalPage()){
				page.start += 1;
				self._render();
			}
		}
		
		self.prev = function(){
			if(page.start > 1){
				page.start -= 1;
				self._render();
			}
		}
		
		self.first = function(){
			page.start = 1;
			self._render();
		}
		
		self.last = function(){
			page.start = self._getTotalPage();
			self._render();
		}
		
		self.go = function(start){
			if(start > 0 && start <= self._getTotalPage()){
				page.start = start;
				self._render();
			}
		}
		
		
		self._getTotalPage = function(){
			var totalPageFloat = (page.total / page.num);
			var totalPage = parseInt(totalPageFloat);
			if(totalPageFloat - totalPage > 0){
				totalPage += 1;
			}
			return totalPage;
		}
		
		self._renderToContainer = function(h){
			switch(opts.renderType){
			case 'append':
				if(opts.animation){
					var objH = $(h);
					objH.css('display','none');
					$(self).append(objH);
					objH.fadeIn('fast');
				}else{
					$(self).append(h);
				}
				break;
			case 'replace':
			default:
				if(opts.animation){
					$(self).fadeOut('fast',function(){
						$(self).html(h);
						$(self).fadeIn('fast');
						opts.event.afterRender();
					});
				}else{
					$(self).html(h);
					opts.event.afterRender();
				}
			}
		}
		
		self.reload = function(){
			page.start = 1;
			$(self).empty();
			self._render();
		}

		self.setData = function(data){
			opts.data = data;
			self._render();
		}
		
		self._render = function(){
			if(opts.data && opts.data.length >= 0){
				//固定数据模式
				var data = {
					data : opts.data
				}
				var h = self.tplRender(data);
				self._renderToContainer(h);
			}else{
				//远程加载模式
				var params = {};
				if($.isFunction(opts.params)){
					params = opts.params();
				}else{
					params = $.extend({},opts.params);
				}
				//insert start into params becase of start from options is fixed
				params[opts.startField] = page.start;
				
				$.ajax(opts.url,{
					data : params,
					dataType :opts.ajax.type,
					success : function(r){
						if(r && r.code=='success'){
							page.total = r.data.recordsTotal;
							var t_page = $.extend({},page);
							opts.event.onDidLoaded(t_page,self._getTotalPage(),r.data.data);
							var h = self.tplRender(r.data);
							self._renderToContainer(h);
							self._renderPaging();
						}
					},
					beforeSend : function(){
						if(layer){
							layer.load(1);
						}
					},
					complete : function (XMLHttpRequest, textStatus) {
						if(layer){
							layer.closeAll('loading');
						}

					}
				});
			}
			
			
		};
		
		self._renderPaging = function(){
			if(opts.pagingId && opts.pagingId != ''){
				
				//calculate paging
				var pagingNums = Array();
				//计算最小页数
				var minPage = parseInt(page.start) - opts.pagingNum;
				if (minPage < 1) {
					minPage = 1;
				}
				var maxPage = parseInt(page.start) + opts.pagingNum;
				if (maxPage > self._getTotalPage()) {
					maxPage = self._getTotalPage();
				}
				for (var i = minPage; i <= maxPage; i++) {
					pagingNums.push(i);
				}
				var pagingData = {}
				pagingData.start = page.start;
				pagingData.data = pagingNums;
				pagingData.last = maxPage;
				var pagingH = self.pagingTplRender(pagingData);
				
				$("#"+opts.pagingId).html(pagingH);
				
			}
		}
		
		return this.each(function(){
			self._init();
			self._render();
		});
	}
	
})(window.jQuery);